@extends('layouts.app')

@section('title', '导出账单')

@section('main-content')
<div class="page-header">
    <button class="back-btn" onclick="window.location.href = '{{ route('user.profile') }}'">‹</button>
    <h1 class="page-title">导出账单</h1>
</div>

<div class="export-section">
    <div class="export-card">
        <h2 class="export-card-title">导出当前账本</h2>
        @if(!Auth::user()->isMember())
            <div class="member-only-notice">
                <div class="notice-icon">👑</div>
                <div class="notice-text">
                    <div class="notice-title">会员专享功能</div>
                    <div class="notice-desc">账单导出功能仅限会员使用</div>
                </div>
                <a href="{{ route('membership.benefits') }}" class="upgrade-btn">立即升级</a>
            </div>
        @else
            <div class="export-form">
                <form id="export-form">
                    @csrf
                    <div class="export-options">
                        <div class="export-option">
                            <input type="radio" id="export-all" name="export_range" value="all" checked>
                            <label for="export-all">导出全部记录</label>
                        </div>
                        <div class="export-option">
                            <input type="radio" id="export-month" name="export_range" value="month">
                            <label for="export-month">导出本月记录</label>
                        </div>
                        <div class="export-option">
                            <input type="radio" id="export-custom" name="export_range" value="custom">
                            <label for="export-custom">自定义时间范围</label>
                        </div>

                        <div class="date-range" id="custom-date-range" style="display: none;">
                            <div class="date-input">
                                <label class="form-label">开始日期</label>
                                <input type="date" class="form-control" id="start-date" name="start_date">
                            </div>
                            <div class="date-input">
                                <label class="form-label">结束日期</label>
                                <input type="date" class="form-control" id="end-date" name="end_date">
                            </div>
                        </div>
                    </div>

                    <div class="export-options">
                        <div class="export-option">
                            <input type="radio" id="export-excel" name="format" value="excel" checked>
                            <label for="export-excel">Excel格式 (.xlsx)</label>
                        </div>
                        <div class="export-option">
                            <input type="radio" id="export-csv" name="format" value="csv">
                            <label for="export-csv">CSV格式 (.csv)</label>
                        </div>
{{--                        <div class="export-option">--}}
{{--                            <input type="radio" id="export-pdf" name="format" value="pdf">--}}
{{--                            <label for="export-pdf">PDF格式 (.pdf)</label>--}}
{{--                        </div>--}}
                    </div>

                    <div class="export-limit-notice">
                        <div class="limit-icon">⏰</div>
                        <div class="limit-text">每日限制导出2次，文件保存3天</div>
                    </div>

                    <button type="submit" class="export-btn" id="submit-export">申请导出</button>
                </form>
            </div>
        @endif
    </div>

    <div class="export-card">
        <h2 class="export-card-title">导出历史</h2>
        <div class="export-history-list" id="export-history-list">
            <div class="loading-placeholder">
                <div class="loading-spinner"></div>
                <div class="loading-text">加载中...</div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
.app-container {
    padding: 0 !important;
    padding-bottom: 80px !important;
}

/* 导出账单页面样式 */
.export-header {
    background: #f8f9fa;
    padding: 20px;
    position: relative;
    border-bottom: 1px solid rgba(0,0,0,0.05);
}

.back-btn {
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 20px;
    color: #4a5568;
    text-decoration: none;
    transition: all 0.3s ease;
}

.back-btn:hover {
    color: #667eea;
    transform: translateY(-50%) scale(1.1);
}

.export-title {
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    color: #2d3748;
    margin: 0;
}

.export-section {
    padding: 20px;
    margin-bottom: 20px;
}

.export-card {
    background: white;
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.export-card:hover {
    box-shadow: 0 6px 25px rgba(0,0,0,0.12);
}

.export-card-title {
    font-size: 16px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 15px;
}

/* 会员专享提示 */
.member-only-notice {
    display: flex;
    align-items: center;
    padding: 20px;
    background: linear-gradient(135deg, #fef3c7, #fde68a);
    border-radius: 12px;
    border: 1px solid #f59e0b;
}

.notice-icon {
    font-size: 32px;
    margin-right: 15px;
}

.notice-text {
    flex: 1;
}

.notice-title {
    font-size: 16px;
    font-weight: 600;
    color: #92400e;
    margin-bottom: 5px;
}

.notice-desc {
    font-size: 14px;
    color: #a16207;
}

.upgrade-btn {
    background: linear-gradient(135deg, #f59e0b, #d97706);
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
}

.upgrade-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(245, 158, 11, 0.4);
    color: white;
    text-decoration: none;
}

.export-form {
    margin-bottom: 20px;
}

.export-options {
    margin-bottom: 15px;
}

.export-option {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.export-option:hover {
    background: #f8fafc;
}

.export-option input[type="radio"] {
    margin-right: 10px;
    transform: scale(1.2);
}

.export-option label {
    font-size: 14px;
    color: #4a5568;
    cursor: pointer;
    flex: 1;
}

.date-range {
    display: flex;
    gap: 10px;
    margin-top: 10px;
    margin-bottom: 15px;
    padding: 15px;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
}

.date-input {
    flex: 1;
}

.form-label {
    display: block;
    margin-bottom: 5px;
    font-size: 12px;
    color: #718096;
    font-weight: 500;
}

.form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.export-limit-notice {
    display: flex;
    align-items: center;
    padding: 12px;
    background: #e6fffa;
    border: 1px solid #81e6d9;
    border-radius: 8px;
    margin-bottom: 15px;
}

.limit-icon {
    font-size: 16px;
    margin-right: 8px;
}

.limit-text {
    font-size: 12px;
    color: #234e52;
}

.export-btn {
    width: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 12px;
    padding: 12px;
    color: white;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    cursor: pointer;
}

.export-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.export-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.export-btn.loading {
    position: relative;
    color: transparent;
}

.export-btn.loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    border: 2px solid transparent;
    border-top: 2px solid white;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 导出历史样式 */
.export-history-list {
    margin-top: 15px;
}

.loading-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: #a0aec0;
}

.loading-spinner {
    width: 20px;
    height: 20px;
    border: 2px solid #e2e8f0;
    border-top: 2px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 10px;
}

.loading-text {
    font-size: 14px;
}

.export-history-item {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 10px;
    position: relative;
    transition: all 0.3s ease;
}

.export-history-item:hover {
    background: #f1f5f9;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.export-history-title {
    font-size: 15px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 5px;
}

.export-history-meta {
    font-size: 12px;
    color: #718096;
    margin-bottom: 10px;
}

.export-history-status {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    margin-bottom: 10px;
}

.status-pending {
    background: #fef3c7;
    color: #d97706;
}

.status-processing {
    background: #dbeafe;
    color: #2563eb;
}

.status-completed {
    background: #d1fae5;
    color: #059669;
}

.status-failed {
    background: #fee2e2;
    color: #dc2626;
}

.status-expired {
    background: #f3f4f6;
    color: #6b7280;
}

.download-btn {
    display: inline-flex;
    align-items: center;
    background: #edf2f7;
    border: none;
    border-radius: 8px;
    padding: 6px 12px;
    font-size: 13px;
    color: #4a5568;
    cursor: pointer;
    transition: all 0.2s ease;
    text-decoration: none;
}

.download-btn:hover {
    background: #e2e8f0;
    color: #2d3748;
    text-decoration: none;
}

.download-btn i {
    margin-right: 5px;
}

.export-empty {
    text-align: center;
    padding: 30px 0;
    color: #a0aec0;
}

.export-empty-icon {
    font-size: 40px;
    margin-bottom: 10px;
}

.export-empty-text {
    font-size: 14px;
}

.countdown {
    font-size: 12px;
    color: #e53e3e;
    margin-top: 5px;
}

.error-message {
    font-size: 12px;
    color: #e53e3e;
    margin-top: 5px;
    padding: 8px;
    background: #fee2e2;
    border-radius: 6px;
}
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // 初始化日期选择器默认值
    const today = new Date();
    const lastMonth = new Date(today);
    lastMonth.setMonth(today.getMonth() - 1);

    $('#start-date').val(formatDate(lastMonth));
    $('#end-date').val(formatDate(today));

    // 切换自定义日期范围显示
    $('input[name="export_range"]').change(function() {
        const customDateRange = $('#custom-date-range');
        if (this.value === 'custom') {
            customDateRange.show();
        } else {
            customDateRange.hide();
        }
    });

    // 提交导出申请
    $('#export-form').submit(function(e) {
        e.preventDefault();

        const submitBtn = $('#submit-export');
        const originalText = submitBtn.text();

        // 验证自定义日期范围
        if ($('input[name="export_range"]:checked').val() === 'custom') {
            const startDate = $('#start-date').val();
            const endDate = $('#end-date').val();

            if (!startDate || !endDate) {
                showAlert('请选择完整的日期范围');
                return;
            }

            if (new Date(startDate) > new Date(endDate)) {
                showAlert('开始日期不能晚于结束日期');
                return;
            }
        }

        // 设置加载状态
        submitBtn.prop('disabled', true).addClass('loading');

        $.ajax({
            url: '{{ route("bill-export.store") }}',
            method: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    showAlert(response.message, 'success');
                    loadExportHistory(); // 重新加载历史记录
                } else {
                    showAlert(response.message || '导出申请失败');
                }
            },
            error: function(xhr) {
                let message = '导出申请失败，请重试';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                showAlert(message);
            },
            complete: function() {
                submitBtn.prop('disabled', false).removeClass('loading');
            }
        });
    });

    // 加载导出历史
    loadExportHistory();

    // 定时刷新状态
    setInterval(loadExportHistory, 30000); // 每30秒刷新一次
});

// 加载导出历史记录
function loadExportHistory() {
    $.ajax({
        url: '{{ route("bill-export.history") }}',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                renderExportHistory(response.data);
            }
        },
        error: function() {
            $('#export-history-list').html('<div class="export-empty"><div class="export-empty-icon">❌</div><div class="export-empty-text">加载失败，请刷新重试</div></div>');
        }
    });
}

// 渲染导出历史列表
function renderExportHistory(exports) {
    const historyList = $('#export-history-list');

    if (exports.length === 0) {
        historyList.html('<div class="export-empty"><div class="export-empty-icon">📄</div><div class="export-empty-text">暂无导出记录</div></div>');
        return;
    }

    let html = '';
    exports.forEach(function(item) {
        let statusClass = 'status-' + item.status;
        let downloadBtn = '';
        let countdownHtml = '';
        let errorHtml = '';

        if (item.status === 'completed' && item.download_url && !item.is_expired) {
            downloadBtn = `<button class="download-btn" onclick="handleDownload('${item.download_url}', ${item.id})">📥 下载</button>`;
            if (item.remaining_time) {
                countdownHtml = `<div class="countdown">文件将在 ${item.remaining_time} 后过期</div>`;
            }
        }

        if (item.status === 'failed' && item.error_message) {
            errorHtml = `<div class="error-message">${item.error_message}</div>`;
        }

        html += `
            <div class="export-history-item">
                <div class="export-history-title">${item.title}</div>
                <div class="export-history-meta">${item.created_at} | ${item.book_name} | ${item.format}</div>
                <span class="export-history-status ${statusClass}">${item.status_text}</span>
                ${countdownHtml}
                ${errorHtml}
                <div>
                    ${downloadBtn}
                </div>
            </div>
        `;
    });

    historyList.html(html);
}

// 检测是否为微信环境
function isWeChat() {
    return /MicroMessenger/i.test(navigator.userAgent);
}

// 显示下载链接弹窗
function showDownloadModal(downloadUrl, filename) {
    const modal = $(`
        <div class="download-modal-overlay" style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
        ">
            <div class="download-modal" style="
                background: white;
                border-radius: 12px;
                padding: 20px;
                margin: 20px;
                max-width: 400px;
                width: 90%;
                text-align: center;
            ">
                <h3 style="margin-bottom: 15px; color: #2d3748;">微信内无法直接下载</h3>
                <p style="margin-bottom: 20px; color: #4a5568; font-size: 14px;">请点击右上角菜单，选择"在浏览器中打开"</p>
                <div style="
                    background: #f7fafc;
                    border: 1px solid #e2e8f0;
                    border-radius: 8px;
                    padding: 10px;
                    margin-bottom: 20px;
                    word-break: break-all;
                    font-size: 12px;
                    color: #2d3748;
                ">${downloadUrl}</div>
                <div style="display: flex; gap: 10px; justify-content: center;">
                    <button class="copy-link-btn" style="
                        background: #667eea;
                        color: white;
                        border: none;
                        border-radius: 6px;
                        padding: 8px 16px;
                        font-size: 14px;
                        cursor: pointer;
                    ">复制链接</button>
                    <button class="close-modal-btn" style="
                        background: #e2e8f0;
                        color: #4a5568;
                        border: none;
                        border-radius: 6px;
                        padding: 8px 16px;
                        font-size: 14px;
                        cursor: pointer;
                    ">关闭</button>
                </div>
            </div>
        </div>
    `);
    
    $('body').append(modal);
    
    // 复制链接
    modal.find('.copy-link-btn').click(function() {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(downloadUrl).then(function() {
                showAlert('链接已复制到剪贴板', 'success');
            }).catch(function() {
                showAlert('复制失败，请手动复制链接');
            });
        } else {
            // 兼容旧浏览器
            const textArea = document.createElement('textarea');
            textArea.value = downloadUrl;
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                showAlert('链接已复制到剪贴板', 'success');
            } catch (err) {
                showAlert('复制失败，请手动复制链接');
            }
            document.body.removeChild(textArea);
        }
    });
    
    // 关闭弹窗
    modal.find('.close-modal-btn, .download-modal-overlay').click(function(e) {
        if (e.target === this) {
            modal.remove();
        }
    });
}

// 处理下载点击事件
function handleDownload(downloadUrl, exportId) {
    // 先获取公开下载链接
    fetch(`/bill-export/${exportId}/public-url`, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.download_url) {
            if (isWeChat()) {
                // 微信环境，显示弹窗
                showDownloadModal(data.download_url, data.filename);
            } else {
                // 普通浏览器，直接下载
                window.location.href = data.download_url;
            }
        } else {
            showAlert(data.message || '获取下载链接失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('获取下载链接失败', 'error');
    });
}

// 格式化日期
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
</script>
@endpush
